#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import COOPGIS_Ajax, COOPGIS_FormMisc, COOPGIS_FormAssembly, COOPGIS_FormCircuitTrace, COOPGIS_FormGeography, COOPGIS_GPS, COOPGIS_Misc
import COOPGIS_DynamicTemplate, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, random
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
import djangoproject.settings
import _mysql as mysql
from models import *
from django import forms
from django.db import transaction




def CircuitAnalysis(request):
    ApplicationName=djangoproject.settings.COOPGISCircuitAnalysisApplicationName
    UserNameOrIPAddress, DefaultMap=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=True, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName)
    Temp, ReadOnlyPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName + 'READONLY')
    Assemblies=None  #Need to Get Station Assemblies to build the form 
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName, DefaultMap, Assemblies=Assemblies) 
    if(not applicationPermission): #Show view of Map and Form if no Permissions, do not perform any form processing
        MapFileName, LayerName=COOPGIS_Misc.GenerateDynamicMapFile(ApplicationName, UserNameOrIPAddress)
        OpenLayersZoom=COOPGIS_Ajax.GetOpenLayersZoom(None, None)
        t = loader.get_template('/opt/coopgis/djangoproject/templates/circuitanalysis.html')
        c = Context({'OpenLayersZoom': OpenLayersZoom, 'CircuitAnalysisForm': form,
                     'MapFileName': MapFileName, 'LayerName': LayerName, 'LoginStatus':LoginStatus})
        return HttpResponse(t.render(c))
    SelectionStation, SelectionSpan, GPSStatus = COOPGIS_FormGeography.SetSelectionStationAndSpan(form)   
    if(SelectionStation):
        Assemblies=Assembly.objects.filter(Station=SelectionStation).order_by('id')
    else:
        Assemblies=None
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName, DefaultMap, Assemblies=Assemblies)   #Rebuild the Form w/ Assembly Information 
    if(not SelectionStation and not SelectionSpan):
        Zoom=15
    else:
        Zoom=23  
    OpenLayersZoom=COOPGIS_Ajax.GetOpenLayersZoom(SelectionStation, SelectionSpan, Zoom=Zoom)  #Get the Zoom before the span is deleted so area is not left on this refresh    
    NumberOfStationAssembliesListedOnForm=COOPGIS_FormAssembly.GetNumberOfStationAssembliesListedOnForm(SelectionStation)
    NumberOfSpanAssembliesListedOnForm=COOPGIS_FormAssembly.GetNumberOfSpanAssembliesListedOnForm(SelectionSpan)
    if(not ReadOnlyPermission):
        COOPGIS_FormGeography.UpdateStationComment(form, SelectionStation, UserNameOrIPAddress)
        COOPGIS_FormGeography.UpdateSpanComment(form, SelectionSpan, UserNameOrIPAddress)
        COOPGIS_FormCircuitTrace.ProcessGeoTrace(form, UserNameOrIPAddress)
    COOPGIS_FormGeography.GetAndSetDefaultMap(form, ApplicationName, UserNameOrIPAddress)
    for assemblyFormNumber in range(0, NumberOfStationAssembliesListedOnForm + 1):
        COOPGIS_FormAssembly.ProcessStationAssembly(form, assemblyFormNumber, SelectionStation, UserNameOrIPAddress)
    for assemblyFormNumber in range(0, NumberOfSpanAssembliesListedOnForm + 1):
        COOPGIS_FormAssembly.ProcessSpanAssembly(form, assemblyFormNumber, SelectionSpan, UserNameOrIPAddress)
    TraceMessage=COOPGIS_FormCircuitTrace.ProcessCircuitTrace(form, UserNameOrIPAddress)
    NewForm=COOPGIS_FormMisc.BuildForm(request, ApplicationName, DefaultMap, Assemblies=Assemblies, station=SelectionStation, span=SelectionSpan) #Rebuild Form Again to get Protected Span Changes
    NewForm=COOPGIS_FormAssembly.CopyPreviousFormInformation(form, NewForm)
    form=NewForm
    COOPGIS_FormMisc.PopulateMiscFormFields(form)
    COOPGIS_FormAssembly.PopulateStationAssemblies(form, SelectionStation, NumberOfStationAssembliesListedOnForm)
    COOPGIS_FormAssembly.PopulateSpanAssemblies(form, SelectionSpan, NumberOfSpanAssembliesListedOnForm)
    COOPGIS_Misc.UpdateSelection(SelectionStation, SelectionSpan, UserNameOrIPAddress)
    COOPGIS_DynamicTemplate.UpdateCircuitAnalysisTemplate(NumberOfStationAssembliesListedOnForm, NumberOfSpanAssembliesListedOnForm, UserNameOrIPAddress)
    MapFileName, LayerName=COOPGIS_Misc.GenerateDynamicMapFile(ApplicationName, UserNameOrIPAddress)
    t = loader.get_template('/opt/coopgis/djangoproject/templates/circuitanalysis' + UserNameOrIPAddress + '.html')
    c = Context({'OpenLayersZoom': OpenLayersZoom, 'form': form, 'TraceMessage': TraceMessage,
                 'LoginStatus':LoginStatus, 'MapFileName': MapFileName, 'LayerName': LayerName,
                 'GPSStatus':GPSStatus})
    return HttpResponse(t.render(c))


class TableRow():
    pass





